package com.mcxx.modules.miniSalvation.order.service.write;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.base.service.read.ActivitiReadService;
import com.mcxx.modules.base.service.read.RuleEngineReadService;
import com.mcxx.modules.miniSalvation.family.service.write.BankWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMainHistoryWriteService;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.dao.read.NoticeBoardReadDao;
import com.mcxx.modules.miniSalvation.order.dto.NoticeBoardDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderStateVerifyDTO;
import com.mcxx.modules.miniSalvation.order.entity.NoticeBoardDetailEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderDetailEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderStateEntity;
import com.mcxx.modules.miniSalvation.order.param.ActivitiParam;
import com.mcxx.modules.miniSalvation.order.service.read.NoticeBoardDetailReadService;
import com.mcxx.modules.miniSalvation.order.service.read.NoticeBoardReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMainHistoryWriteService;
import com.mcxx.modules.temporary.fundpay.service.read.TmpFundPayReadService;
import com.mcxx.modules.temporary.order.dto.TmpOrderStateVerifyDTO;
import com.mcxx.modules.temporary.order.entity.TmpOrderEntity;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderWriteService;
import com.mcxx.modules.temporary.salary.dao.write.TmpFamilySalaryWriteDao;
import com.mcxx.modules.temporary.salary.dao.write.TmpMemberSalaryWriteDao;
import com.mcxx.modules.temporary.salary.entity.TmpFamilySalaryEntity;
import com.mcxx.modules.temporary.salary.entity.TmpMemberSalaryEntity;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.component.message.send.util.MessageSendUtil;
import com.yinhai.ta404.component.message.vo.NoticeVo;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("noticeBoardFinalyWriteService")
@TaTransactional
public class NoticeBoardFinalyWriteService {

    @Autowired
    private NoticeBoardReadService noticeBoardReadService;
    @Autowired
    private NoticeBoardWriteService noticeBoardWriteService;
    @Autowired
    private NoticeBoardDetailReadService noticeBoardDetailReadService;
    @Autowired
    private NoticeBoardDetailWriteService noticeBoardDetailWriteService;
    @Autowired
    private ActivitiReadService activitiReadService;
    @Autowired
    private TmpOrderWriteService tmpOrderWriteService;
    @Autowired
    private TmpOrderReadService tmpOrderReadService;
    @Autowired
    private OrderDetailWriteService orderDetailWriteService;
    @Autowired
    private TmpFamilyMainHistoryWriteService tmpFamilyMainHistoryWriteService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private RuleEngineReadService ruleEngineReadService;
    @Autowired
    private TmpFamilySalaryWriteDao tmpFamilySalaryWriteDao;
    @Autowired
    private TmpMemberSalaryWriteDao tmpMemberSalaryWriteDao;
    @Autowired
    private OrderWriteService orderWriteService;

    public void finishBatch(List<NoticeBoardDetailEntity> batchNoList, UserAccountVo userAccountVo, String batchId,
                            String finishRemark) {

        NoticeBoardDTO noticeBoardDTO = noticeBoardReadService.queryByBatchId(batchId);
        try{

            boolean b = this.exceOrderOther(batchId, userAccountVo, batchNoList,noticeBoardDTO.getBusinessType());

            if(b){

                int rst = noticeBoardWriteService.updateStatusByBatchId(batchId, Constant.NoticeBoardState.COMPLETE,
                                                                        finishRemark);
                if(rst <= 0){

                    throw  new BizException("-1","批次号:{"+batchId+"},更新状态失败");
                }
                if(CollectionUtils.isNotEmpty(batchNoList)){
                    int i = noticeBoardDetailWriteService.updateBatchId(batchNoList);
                    if(i <= 0){
                        throw  new BizException("-1","批次号:{"+batchId+"},更新状态失败");
                    }
                }

                NoticeVo noticeVo = new NoticeVo();
                noticeVo.setTitle("结束公示完成告知");
                noticeVo.setContent("执行批次号为《"+noticeBoardDTO.getBatchNo()+"》,已执行完成");
                MessageSendUtil.sendNotice(userAccountVo.getUserId(), noticeVo);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    public boolean exceOrderOther(String batchId,
                                  UserAccountVo userAccountVo,
                                  List<NoticeBoardDetailEntity> changeDateList,
                                  String businessType){

        List<OrderDTO> orderDTOList = noticeBoardReadService.getOrderStateAndVersions(batchId,
                Constant.BusinessCode.LINSHI.equals(businessType) ? "BCX56" : "BAX21");

        List<OrderDTO> orderDTOListBack = new ArrayList<>();
        orderDTOListBack.addAll(orderDTOList);

        List<OrderDTO> singelOrder = new ArrayList<>();


        OrderDetailEntity orderDetailEntity = Constant.BusinessCode.LINSHI.equals(businessType) ? this.setDetailEntity(userAccountVo) : null;

        this.orderListFilterChage(changeDateList,orderDTOList,singelOrder,userAccountVo,businessType);
        if(CollectionUtils.isNotEmpty(singelOrder)){

            boolean b = this.updateOrderChange(singelOrder, userAccountVo,orderDetailEntity,businessType);

            if(!b){
                throw  new BizException("-1","批次号:{"+batchId+"},更新业务状态失败");
            }

            this.updateOrderState(batchId, orderDTOList,userAccountVo,orderDetailEntity,businessType);
            return true;
        }else{

            this.updateOrderState(batchId, orderDTOList, userAccountVo,orderDetailEntity,businessType);
            return true;
        }
    }

    public OrderDetailEntity setDetailEntity(UserAccountVo userAccountVo){
        OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
        orderDetailEntity.setCheckDate(new Date());
        orderDetailEntity.setOperator(userAccountVo.getUsername());
        orderDetailEntity.setCreateBy(userAccountVo.getUserId());
        orderDetailEntity.setOrgId(userAccountVo.getOrgId());

        orderDetailEntity.setBusinessStatus(Constant.RemarkOperType.STREET);

        orderDetailEntity.setCheckType(Constant.CheckDatailStatus.NOTICE_he);

        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){

            orderDetailEntity.setBusinessStatus(Constant.RemarkOperType.COUNTY);
            orderDetailEntity.setCheckType(Constant.CheckDatailStatus.NOTICE_Pi);
        }
        return orderDetailEntity;
    }


    public void updateOrderState(String batchId, List<OrderDTO> orderDTOList,
                                  UserAccountVo userAccountVo,
                                  OrderDetailEntity orderDetailEntity,
                                  String businessType){


        if(null != userAccountVo){
            List<OrderDetailEntity> detailList = new ArrayList<>();
            for(OrderDTO orderDTO : orderDTOList){
                NoticeBoardDetailEntity noticeBoardDetailEntity = noticeBoardDetailReadService.queryDetailByOrderId(batchId, orderDTO.getId());

                if(Constant.BusinessCode.LINSHI.equals(businessType)){

                    TmpOrderStateVerifyDTO orderState = tmpOrderReadService.getBizStateReportFile(orderDTO.getId());
                    String bizStateType = Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())?Constant.TmpOrderBizStateType.COMPLETE_NOTICE:Constant.TmpOrderBizStateType.COMPLETE_NOTICE_COUNTRY;
                    ruleEngineReadService.getTempBizStateRuleThrow(bizStateType, orderState, userAccountVo);
                    TmpOrderEntity orderEntity = new TmpOrderEntity();
                    orderEntity.setBizState(orderState.getNextBizState());

                    orderEntity.setFinishLevel(userAccountVo.getAreaLevel());

//                    String startMonth = DateUtil.date2Str(noticeBoardDetailEntity.getSaveDate(), sdf2);
                      orderEntity.setId(orderState.getOrderId());




                      tmpOrderWriteService.updateOrder(orderEntity);



//                    tmpFamilySalary.setOrderId(orderDTO.getId());




//                    tmpMemberSalary.setOrderId(orderDTO.getId());




//                    tmpFamilyMainHistoryWriteService.backHistory(orderDTO,orderDTO.getFamilyId(), userAccountVo);

                }else{


                    OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderDTO.getId());
                    orderStateVerifyDTO.setNextCondition(noticeBoardDetailEntity.getCheckResult());

                    String bizStateType = Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())
                            ? Constant.OrderBizStateType.COMPLETE_NOTICE
                            : Constant.OrderBizStateType.COMPLETE_NOTICE_COUNTRY;

                    ruleEngineReadService.getBizStateRuleThrow(bizStateType, orderStateVerifyDTO, userAccountVo);


                    OrderEntity updateOrderEntity = new OrderEntity();
                    updateOrderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
                    updateOrderEntity.setVersion(orderStateVerifyDTO.getVersion());
                    updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
                    updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
                    orderWriteService.updateIgnoreNull(updateOrderEntity);
                }
            }
        }
    }


    public boolean updateOrderChange(List<OrderDTO> singelOrderList,
                                     UserAccountVo userAccountVo,
                                     OrderDetailEntity orderDetailEntity,
                                     String businessType){

        for(OrderDTO orderDTO:singelOrderList){
            String bizState = orderDTO.getBizState();
            OrderStateEntity orderStateEntity = new OrderStateEntity(orderDTO.getId(), bizState, null, orderDTO.getVersion());
            orderStateEntity.setState(bizState);

            orderStateEntity.setFinishLevel(userAccountVo.getAreaLevel());

            if(Constant.BusinessCode.LINSHI.equals(businessType)){
//                orderStateEntity.setStartMonth(orderDTO.getStartMonth());
//                orderStateEntity.setEndMonth(orderDTO.getEndMonth());


                int cnt = tmpOrderWriteService.updateState(orderStateEntity);
                if(cnt <= 0){
                    throw new BizException("-1", "修改业务的状态异常");
                }


//                tmpFamilySalary.setOrderId(orderDTO.getId());
//                tmpFamilySalary.setStartDate(orderDTO.getStartMonth());
//                tmpFamilySalary.setEndDate(orderDTO.getEndMonth());


//                tmpMemberSalary.setOrderId(orderDTO.getId());
//                tmpMemberSalary.setStartDate(orderDTO.getStartMonth());
//                tmpMemberSalary.setEndDate(orderDTO.getEndMonth());


            }else{

                orderWriteService.updateState(orderStateEntity);

                //familyMainHistoryWriteService.backHistory(orderDTO.getId(),orderDTO.getFamilyId(),orderDTO.getStartMonth())

            }

        }
        return true;
    }


    public void orderListFilterChage(List<NoticeBoardDetailEntity> changeDateList,
                                 List<OrderDTO> orderDTOList,
                                 List<OrderDTO> singelOrderList,
                                 UserAccountVo userAccountVo,
                                 String businessType){
        for(NoticeBoardDetailEntity en : changeDateList){
            for(int i = 0 ; i < orderDTOList.size(); i++){
                OrderDTO orderDTO = orderDTOList.get(i);

//                if(Constant.BizState.APPROVE_REJECT.equals(orderDTO.getState())){




//                if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())
//                        && !Constant.BusinessCode.LINSHI.equals(noticeBoardDTO.getBusinessType())){
//                    int i = fundPayReadService.verifyFunPay(noticeBoardDTO.getBusinessType(), userAccountVo.getAreaCode(), DateUtil.getCurrentDate(), "01");



                if(en.getOrderId().equals(orderDTO.getId())){

                    OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(en.getOrderId());
                    orderStateVerifyDTO.setNextCondition(en.getCheckResult());
                    String bizStateType = Constant.OrderBizStateType.COMPLETE_NOTICE;
                    ruleEngineReadService.getBizStateRuleThrow(bizStateType, orderStateVerifyDTO, userAccountVo);


                    orderDTO.setBizState(orderStateVerifyDTO.getNextBizState());
                    //orderDTO.setState(orderStateVerifyDTO.getNextState());

                    if(Constant.BusinessCode.LINSHI.equals(businessType)){

                        ActivitiParam activitiParam = new ActivitiParam(orderDTO.getBizState(),
                                en.getCheckResult(),
                                orderDTO.getSalvMoney(),
                                businessType);

                        String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());
                        if("-1".equals(nextActviti)){
                            throw new BizException("-1", "账号没有保存审核信息的信息");
                        }
                        SimpleDateFormat sdf5 = new SimpleDateFormat("yyyyMM");
                        orderDTO.setStartMonth(sdf5.format(en.getSaveDate()));
                        orderDTO.setEndMonth(sdf5.format(en.getSaveDate()));
                        orderDTO.setEndDate(sdf5.format(en.getSaveDate()));
                        orderDTO.setReason(en.getRemark());
                        orderDTO.setBizState(nextActviti);
                    }
                    singelOrderList.add(orderDTO);
                    orderDTOList.remove(i);
                    break;
                }

            }
        }
    }
}
